package com.rzjm.api.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rzjm.api.config.RequestDataHelper;
import com.rzjm.api.constant.ResponseCode;
import com.rzjm.api.entity.*;
import com.rzjm.api.entity.dto.ParameterDto;
import com.rzjm.api.service.*;
import com.rzjm.api.util.GsonResultBean;
import com.rzjm.api.util.OssUtil;
import com.rzjm.api.util.Tools;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;

/**
 *@Author: ZhouWei
 *@Description:  调查问卷相关接口
 *@Date 2018-05-10
 */
@Component
@RestController
@RequestMapping("/survey")//url:模块/资源/{}/细分
public class SurveyController extends BaseController {

    @Resource
    private UserService userService;
    @Resource
    private SysUserService sysUserService;
    @Resource
    private CitizenService citizenService;
    @Resource
    private TownsService townsService;
    @Resource
    private SurveyService surveyService;
    @Resource
    private SurveyQuestionService questionService;
    @Resource
    private SurveyUserRecordService surveyUserRecordService;
    @Resource
    private SurveyUserRecordInfoService surveyUserRecordInfoService;
    @Resource
    private ParameterService parameterService;
    @Resource
    private SysDictService sysDictService;


    @Value("${web.uploadPath}")
    private String uploadPath;//图片地址
    @Value("${web.imgprefix}")
    private String imgPrefix;//图片地址
    /**
     *  问卷列表
     * @param
     * @throws Exception
     */
    @PostMapping(value = "/list")
    public JSONObject list(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            logBefore(logger, "survey/list 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }
            List<Survey> surveys = surveyService.selectListByColumn("state",0);
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",surveys.size(),surveys),false,false);
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }


    /**
     *  问卷列表
     * @param
     * @throws Exception
     */
    @PostMapping(value = "/question/list")
    public JSONObject questionList(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            logBefore(logger, "survey/list 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            Integer survey_id = jsonRequest.containsKey("survey_id") ? jsonRequest.getInt("survey_id") : 0;
            Integer room_id = jsonRequest.containsKey("room_id") ? jsonRequest.getInt("room_id") : 0;
            Integer btn_type = jsonRequest.containsKey("btn_type") ? jsonRequest.getInt("btn_type") : 0;
            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            Survey survey = surveyService.findById(survey_id);
            if(survey == null){
                QueryWrapper<Survey> qw = new QueryWrapper<>();
                qw.eq("is_default",1);
                qw.eq("use_type",btn_type);
                survey = surveyService.getOne(qw);
                if(survey == null){
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该问卷不存在"),true,true);
                }else{
                    survey_id = survey.getId();
                }
            }

            Citizen citizen = citizenService.findById(room_id);
            if(citizen!=null){
                SysDict sysDict = sysDictService.getTypeByTypeAndValue("room_type",citizen.getRoomType().toString());
                if(sysDict!=null){
                    citizen.setRoomTypeName(sysDict.getName());
                }

                SysDict sysDict1 = sysDictService.getTypeByTypeAndValue("heating_mode",citizen.getHeatingMode().toString());
                if(sysDict1!=null){
                    citizen.setHeatingModeName(sysDict1.getName());
                }
            }

            QueryWrapper<SurveyQuestion> qw = new QueryWrapper<>();
            qw.eq("survey_id",survey_id);
            qw.eq("state",1);
            qw.orderByAsc("sort");
            List<SurveyQuestion> questions = questionService.list(qw);
            if(CollUtil.isNotEmpty(questions)){
                for (SurveyQuestion question : questions){
                    if(StrUtil.isNotEmpty(question.getAnswerSection())){
                        JSONArray jsonArray = JSONUtil.parseArray(question.getAnswerSection());
                        question.setSections(jsonArray);
                    }else{
                        question.setSections(new JSONArray());
                    }
                    question.setCheckBoxs(new ArrayList<>());
                    question.setFileList(new ArrayList<>());
                }
            }
            Map<String,Object> map = new HashMap<>();
            map.put("questions",questions);
            map.put("survey",survey);
            map.put("citizen",citizen);

            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",questions.size(),map),false,false);
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     * 问卷详情
     * @param
     * @throws Exception
     */
    @PostMapping(value="/detail")
    public JSONObject detail(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            logBefore(logger, "survey/detail 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int survey_id = jsonRequest.containsKey("survey_id") ? jsonRequest.getInt("survey_id") : 0;
            int question_id = jsonRequest.containsKey("question_id") ? jsonRequest.getInt("question_id") : 0;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            Survey survey = surveyService.findById(survey_id);
            if(survey == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该问卷内容不存在"),true,true);
            }

            SurveyQuestion question = questionService.findById(question_id);
            if(question == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该问卷内容不存在"),true,true);
            }

            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",question),true,false);
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }


    /**
     * 防护措施
     * @param
     * @throws Exception
     */
    @PostMapping(value="/measure")
    public JSONObject measure(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            logBefore(logger, "survey/detail 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            ParameterDto parameterDto = new ParameterDto();
            Parameter parameter = parameterService.findById(1);
            if(parameter!=null){
                parameterDto.setConservatoryMeasure(parameter.getConservatoryMeasure());
            }

            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",parameterDto),true,false);
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     *  问卷列表
     * @param
     * @throws Exception
     */
    @PostMapping(value = "/question/record/list")
    public JSONObject questionRecordList(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            logBefore(logger, "survey/list 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int pageIndex = jsonRequest.containsKey("pageIndex") ? jsonRequest.getInt("pageIndex") : 0;
            int pageSize = jsonRequest.containsKey("pageSize") ? jsonRequest.getInt("pageSize") : 0;
            String keyword = jsonRequest.containsKey("keyword") ? jsonRequest.getStr("keyword") : null;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            QueryWrapper<SurveyUserRecord> qw = new QueryWrapper<>();
            qw.eq("wx_user_id",user_id);
            if(StrUtil.isNotEmpty(keyword)){
                qw.and(wrapper ->
                        wrapper.like("holder_name",keyword).or().like("holder_phone",keyword)
                                .or().like("room_no",keyword)
                );
            }
            qw.orderByDesc("create_time");
            List<SurveyUserRecord> records = surveyUserRecordService.getPageEntityList(qw,pageIndex,pageSize);
            if(CollUtil.isNotEmpty(records)){
                for (SurveyUserRecord question : records){
                    Citizen citizen = citizenService.findById(question.getRoomId());
                    if(citizen!=null){
                        question.setRoomNo(citizen.getRoomNo());
                        question.setHolderName(citizen.getHolderName());
                        question.setHolderPhone(citizen.getHolderPhone());
                    }
                    Towns town = townsService.findById(question.getTownId());
                    if(town!=null){
                        question.setTownName(town.getTownName());
                    }
                    Towns village = townsService.findById(question.getVillageId());
                    if(village!=null){
                        question.setVillageName(village.getTownName());
                    }
                }
            }
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",records.size(),records),false,false);
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     *  问卷列表
     * @param
     * @throws Exception
     */
    @PostMapping(value = "/question/record/detail")
    public JSONObject questionRecordDetail(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            logBefore(logger, "survey/list 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int recordId = jsonRequest.containsKey("recordId") ? jsonRequest.getInt("recordId") : 0;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }


            SurveyUserRecord record = surveyUserRecordService.findById(recordId);
            if(record != null){
                Map<String,Object> map = new HashMap<>();
                map.put("survey_user_record_info", record.getRecordTableName());
                RequestDataHelper.setRequestData(map);
            }


            QueryWrapper<SurveyUserRecordInfo> qw = new QueryWrapper<>();
            qw.eq("record_id",recordId);
            List<SurveyUserRecordInfo> records = surveyUserRecordInfoService.list(qw);
            if(CollUtil.isNotEmpty(records)){
                for (SurveyUserRecordInfo recordInfo : records){
                    SurveyQuestion question = questionService.findById(recordInfo.getQuestionId());
                    if(question!=null){
                        recordInfo.setQuestionTitle(question.getQuestion());
                        if(question.getQuestionType() == 0){//单选题
                            if(StrUtil.isNotEmpty(question.getAnswerSection())){
                                JSONArray jsonArray = JSONUtil.parseArray(question.getAnswerSection());
                                if(jsonArray.size() > 0){
                                    Integer answer = Integer.parseInt(recordInfo.getAnswer());
                                    List<String> answers = new ArrayList<>();
                                    for (int i=0;i<jsonArray.size();i++){
                                        if(i == answer){
                                            JSONObject jsonObject = JSONUtil.parseObj(jsonArray.get(i));
                                            answers.add(jsonObject.getStr("value"));
                                            recordInfo.setAnswers(answers);
                                        }
                                    }
                                }
                            }
                        }else if(question.getQuestionType() == 1) {//输入题
                            List<String> answers = new ArrayList<>();
                            answers.add(recordInfo.getAnswer());
                            recordInfo.setAnswers(answers);
                        } else if(question.getQuestionType() == 2) {//多选题
                            if(StrUtil.isNotEmpty(question.getAnswerSection())){
                                JSONArray jsonArray = JSONUtil.parseArray(question.getAnswerSection());
                                if(jsonArray.size() > 0){
                                    List<Integer> answerValues = JSONUtil.toList(recordInfo.getAnswer(),Integer.class);

                                    List<String> answers = new ArrayList<>();
                                    for (Integer index : answerValues){
                                        for (int i = 0;i < jsonArray.size();i++){
                                            if(i == index){
                                                JSONObject jsonObject = JSONUtil.parseObj(jsonArray.get(i));
                                                answers.add(jsonObject.getStr("value"));
                                            }
                                        }
                                    }
                                    recordInfo.setAnswers(answers);
                                }
                            }

                        }else if(question.getQuestionType() == 3) {//图片
                            List<String> answers = new ArrayList<>();
                            if(StrUtil.isNotEmpty(recordInfo.getAnswer())) {
                                List<String> answerTemps = JSONUtil.toList(recordInfo.getAnswer(), String.class);
                                for (String img : answerTemps){
                                    img = imgPrefix + img;
                                    answers.add(img);
                                }
                            }
                            recordInfo.setAnswers(answers);
                        }
                    }
                }
            }
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",records.size(),records),false,false);
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     * 问卷详情
     * @param
     * @throws Exception
     */
    @PostMapping(value="/addRecord")
    public JSONObject addRecord(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            logBefore(logger, "survey/detail 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int survey_id = jsonRequest.containsKey("survey_id") ? jsonRequest.getInt("survey_id") : 0;
            int roomId =  jsonRequest.containsKey("room_id") ? jsonRequest.getInt("room_id") : 0;
            double lng =  jsonRequest.containsKey("lng") ? jsonRequest.getDouble("lng") : 0;
            double lat =  jsonRequest.containsKey("lat") ? jsonRequest.getDouble("lat") : 0;
            String answer = jsonRequest.containsKey("answer") ? jsonRequest.getStr("answer") : null;
            int check_type = jsonRequest.containsKey("check_type") ? jsonRequest.getInt("check_type") : 0;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            SysUser sysUser = sysUserService.selectByUniqueColumn("user_id",user.getSysUserId());
            if(sysUser == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"您未绑定企业人员"),true,true);
            }


//            QueryWrapper<SurveyUserRecord> qw = new QueryWrapper<>();
//            qw.eq("survey_id",survey_id);
//            qw.eq("room_id",room_id);
//            long recordCount = surveyUserRecordService.count(qw);
//            if(recordCount > 0){
//                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该户已参与过调查问卷"),true,true);
//            }

            if(StrUtil.isEmpty(answer)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"请输入答案"),true,true);
            }

            Survey survey = surveyService.findById(survey_id);
            if(survey == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该问卷不存在"),true,true);
            }

            //int surveyId, Integer roomId, User user, SysUser sysUser, Double lng, Double lat, String answer
            int ret = surveyUserRecordService.addRecord(survey_id,roomId, user,sysUser,lng,lat,answer,check_type);
            if(ret > 0){
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"谢谢参与，提交成功"),true,true);
            }else{
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"请求失败"),true,true);
            }
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }



    /** 巡检记录的图片上传
     * @param
     * @throws Exception
     */
    @PostMapping(value="/uploadImg")
    public JSONObject uploadImg(HttpServletRequest request) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            String img_key = "";
            // 创建一个通用的多部分解析器.
            CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
            // 设置编码
            commonsMultipartResolver.setDefaultEncoding("utf-8");
            // 判断是否有文件上传
            if (commonsMultipartResolver.isMultipart(request)) {//有文件上传
                //将request变成多部分request
                MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;
                //获取multiRequest 中所有的文件名
                Iterator<String> iter = multiRequest.getFileNames();
                if (iter.hasNext()) {
                    Map<String, MultipartFile> maps = multiRequest.getFileMap();
                    for(String key : maps.keySet()) {
                        MultipartFile certurl = maps.get(key);
                        if (!certurl.isEmpty()) {
                            String prefix = certurl.getOriginalFilename().substring(certurl.getOriginalFilename().lastIndexOf(".") + 1);
                            if ("jpeg".equals(prefix) || "jpg".equals(prefix) || "png".equals(prefix)) {
                                String fileName = "survey_img_" + new Date().getTime() + "." + prefix;// user_photo.getOriginalFilename();
                                try {
                                    byte[] byteImg = certurl.getBytes();
                                    if (byteImg != null) {
                                        //上传头像到OSS
                                        int upload_type = OssUtil.TYPE_SURVEY_PHOTOS;
                                        img_key = OssUtil.getUploadPrefix(upload_type) + fileName;
                                        String filePath = uploadPath + img_key;
                                        FileOutputStream out = new FileOutputStream(filePath);
                                        out.write(certurl.getBytes());
                                        out.flush();
                                        out.close();
                                    }
                                } catch (IOException e) {
                                    result = Tools.getJson(new GsonResultBean<>(-4, "系统异常"), true, true);
                                    e.printStackTrace();
                                }
                            }
                        }
                    }
                }
            }
            return Tools.getJson(new GsonResultBean<>(ResponseCode.OK, "图片上传成功",img_key), true, false);
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            logger.error(e.toString(), e);
            System.out.println(""+e.getMessage());
        }
        return result;
    }

}
